<template>
    <div class="refresh-warp"
    ref="scrollBox"
    :style="style"
    @touchstart="start"
    @touchmove="move"
    @touchend="end">
        <div class="refreshing-box">
            <div v-if="state < 2">{{state === 0 ? '下拉即可刷新...' : '释放即可刷新...'}}</div>
            <div v-else>
                <span>
                    <i class="iconfont icon-xiaojuchang"></i>
                </span>
                加载中...
            </div>
        </div>
        <div class="present-box">
            <slot></slot>
        </div>
    </div>
</template>

<script>
export default {
    name: 'RefreshWarp',
    data() {
        return {
            startY: 0,
            moveDistance: 0,
            state: 0,
            duration: 0
        }
    },
    computed: {
        style() {
            return {
                transition: `${this.duration}ms`,
                transform: `translate3d(0,${this.moveDistance}px,0)`
            }
        }
    },
    methods: {
        start(e) {
            this.duration = 0
            this.moveDistance = 0
            this.startY = e.targetTouches[0].clientY
        },
        move(e) {
            let top = document.documentElement.scrollTop || document.body.scrollTop
            if(top > 0) return
            let move = e.targetTouches[0].clientY - this.startY
            if(move > 0) {
                e.preventDefault()
                this.moveDistance = Math.pow(move,0.8)
                if(this.moveDistance > 50) {
                    if(this.state === 1) return
                    this.state = 1
                }else {
                    if(this.state === 0) return
                    this.state = 0
                }
            }
        },
        end() {
            this.duration = 300
            if(this.moveDistance > 50) {
                this.state = 2
                this.moveDistance = 50
                this.$emit('refresh', () => {
                    this.state = 0
                })
            }else {
                this.moveDistance = 0
            }
        }
    },
    watch: {
        state(e) {
            if(e === 0 && this.duration === 300) {
                this.moveDistance = 0
            }
        }
    }
}
</script>

<style lang="scss" scoped>
@import '../../assets/scss/theme.scss';
.refresh-warp{

    display: flex;
    height: calc(100vh - 56px);
    flex-direction: column;
    margin-top:-56px;
    .refreshing-box{
        height: 56px;
        line-height: 56px;
        font-size: 14px;
        @include font_color('font_color11');
        @include background_color('background_color5');
        text-align: center;
        .iconfont{
            animation: spin 5s infinite;
        }
    }
    .present-box{
        height:calc(100vh - 50px);
    }
}
@keyframes spin{
    from {
        transform:rotate(0);
    }
    to {
        transform:rotate(360deg);
    }
}
</style>